package com.kharthick.pwGame.rules;

import java.util.List;
import java.util.Vector;

import com.kharthick.game.Core;
import com.kharthick.pwGame.map.Map;
import com.kharthick.pwGame.map.Tile;
import com.kharthick.pwGame.players.Player;
import com.kharthick.pwGame.units.Unit;

public class AttackRules implements Rules {
	public final int TILE_SIZE = 50;
	int row, col;
	Unit selectedUnit;
	int targetX;
	int targetY;
	int selectedX;
	int selectedY;
	List<Player> players;
	
	public boolean actionOk(Unit u, int x, int y, List<Player> players) {
		selectedUnit = u;
		targetX = x;
		targetY = y;
		Vector<Integer> pos = selectedUnit.getPosition();
		selectedX = pos.get(0);
		selectedY = pos.get(1);
		this.players = players;
		
		row = x/TILE_SIZE;
		col = y/TILE_SIZE;
		
		boolean inRange = YesNo.inRange(u.getPosition(), row, col, u.getRange());
		if(!inRange){
			return false;
		}
		
		boolean empty = YesNo.empty(x, y, players);
		if (empty){
			return false;
		}
		
		//System.out.println(row + ", " + selectedX + ";" + col + ", " + selectedY);
		if(row == selectedX && col == selectedY){
			return false;
		}
		
		return true;
	}
	
	public void doAction(Map m) {
		
//		int aX = sX - scrollX, aY = sY - scrollY;
//		int hX = cX - scrollX, hY = cY - scrollY;
		int attack = selectedUnit.getAttack();
		Unit targetUnit = YesNo.targetPlayer.getUnitByScreenPosition(targetX, targetY);
		int Hp = targetUnit.getHp();
		String sType = selectedUnit.getType(); //uses range to check for unit type
		String aType = targetUnit.getType();//which determines if there is a bonus
		double unitBonus, damage;
		
		if(sType == "Soldier" && aType == "Archer") 
			unitBonus = 1.5;
		else if(sType == "Archer" && aType == "Catapult") 
			unitBonus = 2.0;
		else if(sType == "Catapult"&& aType == "Soldier") 
			unitBonus = 1.5;
		else 
			unitBonus = 1;
		
		Tile t = m.getTileByScreenPosition(selectedX * TILE_SIZE, selectedY * TILE_SIZE);
		int tileAttackBonus = t.TILE_ATTACK_BONUS;
		int tileDefenseBonus = t.TILE_DEFENSE_BONUS;
		//System.out.println(t.TILE_ATTACK_BONUS + ", " + t.TILE_DEFENSE_BONUS);
		
		damage = attack * unitBonus * tileAttackBonus;
		System.out.println(damage + "," + attack + "," + unitBonus + "," + tileAttackBonus);
		
		targetUnit.setHp((int)(Hp - damage));
		if((int)(Hp - damage) <= 0){
			YesNo.targetPlayer.addDeadUnit(targetUnit);
			YesNo.targetPlayer.removeUnit(targetUnit);
		}		
		selectedUnit.activateAttack(targetX, targetY);
		//buffer.drawString("Damage: " + damage, aX*blockSize, aY*blockSize-20);
		//System.out.println("Damage aX " + aX + ", aY " + aY + "; hX " + hX + ", hY " + hY);
	}
}
